<template>
	<view>
		<!-- 替换仓库选择部分 -->
		<view v-if="isAdmin" class="tab-container">
			<scroll-view class="tab-scroll" scroll-x="true" :scroll-left="scrollLeft" :show-scrollbar="false">
				<view class="tab-content">
					<span 
						v-for="(item,index) in list_site" 
						:key="index" 
						@click="choose(item.id)"
						:class="item.handle ? 'choose_bg' : 'bg'"
						class="tab-item"
					>{{item.text}}</span>
				</view>
			</scroll-view>
		</view>
		<view v-else class="tab">
			<span class="normalBg" style="width: 50%;">{{params.site_id}}仓</span>
		</view>
		
		<view class="middle">
			<view class="title">
				<view style="width: 20%;">舍号</view>
				<view style="width: 20%;">笼号</view>
				<view style="width: 20%;">时间</view>
				<view style="width: 40%;">操作</view>
			</view>
			<u-loading class="loading" mode="circle" v-if="isLoading" size="36" color="blue"></u-loading>
			<template v-else>
				<view v-if="!egg_warn_list.length" class="loading">暂无数据</view>
				<template v-else>
					<scroll-view v-if="egg_warn_list.length" scroll-y="true" style="height: 70vh;">
						<view class="title" v-for="i in egg_warn_list" :key="i.id"
							style="background-color: #fff; color: #000">
							<view style="width: 20%;">{{format(i.house_id,params.site_id)}}</view>
							<view style="width: 20%;">{{i.cage_id}}</view>
							<view style="width: 20%;">{{formatDate(i.egg_time)}}</view>
							<view style="width: 40%;">
								<!-- <u-button type="primary" size="mini">编辑</u-button> -->
								<u-button type="error" size="mini" @click="del(i.id)">删除</u-button>
								<!-- </span> -->
							</view>
						</view>
						<view class="middle_bottom" v-show="params.page === totalPage">我也是有底线的~</view>
					</scroll-view>
				</template>
			</template>
		</view>
		<u-modal v-model="isModal" @confirm="confirm" ref="uModal" :async-close="true" :content="content"
			:show-cancel-button="true"></u-modal>
		<!-- 分页-->
		<view class="bottom">
			<Pagination :pageNo="params.page" :pageSize="params.pageSize" :total="total" :continues="3"
				@getPageNo="selectPage">
			</Pagination>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import {
		reqDelWarn,
		reqPostWarnList,
		reqWarnList,
		reqPCWarnList	} from '@/api/index.js'
	import{
		state,
		mutations,
		actions,
	}from '@/store/modules/eggWarning.js'
	import {
		format
	} from '@/utils/format_HouseId.js'
	import Pagination from '@/components/pagination/pagination.vue'
	import Cookie from '@/utils/cookie.js'
	
	export default {
		components: {
			Pagination
		},
		data() {
			return {
				isModal: false,
				content: ' 确认删除这条记录吗？',
				// 存储对应预警信息的id便于删除操作
				id: '',
				list_site: [], // 动态生成的仓库列表
				params: {
					site_id: null, // 当前选中的仓库ID
					page: 1,
					pageSize: 20
				},
				egg_w: [],
				formData:{
					site_id:'',
					house_id:'',
					cage_id:'',
					egg_time:'',
					ststu:'',
					diffInDays:''
				},
				scrollLeft: 0
			};
		},
		computed: {
			...mapGetters(['egg_warn_list', 'total', 'isLoading', 'allSites', 'operationSiteId']),
			totalPage() {
				//向上取证
				return Math.ceil(this.total / this.params.pageSize);
			},
			// 判断是否为管理员
			isAdmin() {
				return Cookie.get('ROLE') === 'admin'
			}
		},
		watch: {
			// 监听仓库列表变化，重新生成仓库选项
			allSites: {
				handler(newVal) {
					console.log('仓库列表变化:', newVal);
					this.generateSiteList();
				},
				deep: true
			},
			// 监听当前操作站点变化
			operationSiteId(newVal) {
				console.log('操作站点变化:', newVal);
				this.generateSiteList();
			}
		},
		created() {
			// 生成仓库列表
			this.generateSiteList();
		},
		mounted() {
			if (this.params.site_id) {
				this.saveWarnList(this.params.site_id);
				this.$store.dispatch('getWarnList', this.params)
			}
		},
		onShow() {
			// 确保页面显示时刷新数据
			this.generateSiteList();
		},
		methods: {
			// 动态生成仓库列表
			generateSiteList() {
				console.log('生成仓库列表 - 开始');
				console.log('当前用户角色:', Cookie.get('ROLE'));
				console.log('allSites:', this.allSites);
				console.log('operationSiteId:', this.operationSiteId);
				
				this.list_site = [];
				
				if (this.isAdmin && this.allSites && this.allSites.length > 0) {
					console.log('管理员模式，显示所有仓库');
					
					// 管理员显示所有仓库
					this.allSites.forEach(site => {
						this.list_site.push({
							id: site,
							text: `${site}仓`,
							handle: site === this.operationSiteId
						});
					});
					
					// 设置默认选中的仓库ID
					this.params.site_id = this.operationSiteId;
				} 
				else if (!this.isAdmin && this.operationSiteId !== undefined && this.operationSiteId !== null) {
					console.log('普通员工模式，显示当前仓库');
					
					// 普通员工只显示自己的仓库
					this.list_site.push({
						id: this.operationSiteId,
						text: `${this.operationSiteId}仓`,
						handle: true
					});
					this.params.site_id = this.operationSiteId;
				}
				// 如果数据有问题，显示默认值
				else {
					console.log('使用默认值');
					this.list_site.push({
						id: 1,
						text: '1仓',
						handle: true
					});
					this.params.site_id = 1;
				}
				
				console.log('生成的仓库列表:', this.list_site);
				console.log('当前选中的site_id:', this.params.site_id);
				
				// 滚动到选中的仓库
				this.$nextTick(() => {
					this.scrollToSelected();
				});
			},
			// 滚动到选中的仓库
			scrollToSelected() {
				const selectedIndex = this.list_site.findIndex(item => item.id === this.params.site_id);
				if (selectedIndex !== -1) {
					// 计算滚动位置，使选中的仓库居中显示
					this.scrollLeft = (selectedIndex - 1) * 150; // 150是每个仓库项的预估宽度
				}
			},
			// 选中仓库号时
			choose(siteId) {
				this.params.site_id = siteId
				// 更新选中状态
				this.list_site.forEach(item => {
					item.handle = item.id === siteId
				})
				// 滚动到选中的位置
				this.$nextTick(() => {
					this.scrollToSelected();
				});
				
				console.log(this.params)
				this.saveWarnList(siteId);
				this.$store.dispatch('getWarnList', this.params)
			},
			// 选中页号时
			selectPage(data) {
				this.params.page = data
				this.$store.dispatch('getWarnList', this.params)
			},
			// 删除预警
			del(id) {
				this.isModal = true
				this.id = id
			},
			confirm() {
				console.log('删除操作传递的id', this.id)
				const obj = {
					id: this.id
				}
				reqDelWarn(obj).then((resp) => {
					console.log(resp)
					if (resp.code === 200) {
						this.isModal = false
						this.$Toast('删除成功')
						this.$store.dispatch('getWarnList', this.params)
					} else {
						this.$Toast('删除失败')
					}
				})
			},
			// 格式化日期
			formatDate(dateStr) {
				const date_left = dateStr.split('T')[0];
				const month = date_left.split('-')[1];
				const day = date_left.split('-')[2];
				return `${month}-${day}`;
			},
			async saveWarnList(siteId){
				let res = await reqPostWarnList({siteId: siteId});
				if(res.code === 200){
					return;
				}
			},
			// 格式化鸽舍
			format(houseId, siteId) {
				console.log(houseId, siteId);
				let rowNum;
				switch (siteId) {
					case 1:
						rowNum = 138;
						break;
					case 2:
						rowNum = 138;
						break;
					case 3:
						rowNum = 138;
						break;
				}
				console.log(houseId, siteId);
				console.log(typeof rowNum);
				if (houseId > rowNum) {
					const hid_sec = houseId % rowNum === 0 ? houseId % rowNum + rowNum : houseId % rowNum;
					const hid_fir = parseInt(houseId % rowNum) === 0 ?
						parseInt(houseId / rowNum) :
						parseInt(houseId /
							rowNum) + 1;
					return `${hid_fir}-${hid_sec}`;
				} else {
					return `1-${houseId}`;
				}
			}
		}
	}
</script>

<style lang="scss">
	.bg {
		background-color: #E8F2FC;
	}

	.choose_bg {
		background-color: #9EB8E3;
	}

	.normalBg {
		display: block;
		background-color: #9EB8E3;
		width: 100%;
		color: #ffffff;
	}

	.tab-container {
		position: sticky;
		top: 0;
		height: 10vh;
		background-color: #fff;
		z-index: 10;
	}

	.tab-scroll {
		width: 100%;
		height: 100%;
		white-space: nowrap;
	}

	.tab-content {
		display: inline-flex;
		align-items: center;
		height: 100%;
		padding: 0 20rpx;

		.tab-item {
			flex-shrink: 0;
			width: 132rpx;
			height: 54rpx;
			margin: 0 10rpx;
			text-align: center;
			line-height: 54rpx;
			border-radius: 10rpx;
			font-weight: bold;
			font-size: 32rpx;
		}
	}

	.tab {
		display: flex;
		position: sticky;
		top: 0;
		justify-content: space-evenly;
		align-items: center;
		height: 10vh;
		background-color: #fff;

		span {
			width: 132rpx;
			height: 54rpx;
			text-align: center;
			line-height: 54rpx;
			border-radius: 10rpx;
			font-weight: bold;
			font-size: 32rpx
		}
	}

	.middle {
		position: relative;
		width: 90%;
		margin: 18.35rpx auto;
		height: 80vh;
		.title {
			display: flex;
			width: 100%;
			padding: 12.84rpx 4.59rpx;
			justify-content: flex-start;
			background-color: #9EB8E3;
			color: #fff;
			font-weight: bold;
			font-size: 20.18rpx;

			view {
				display: flex;
				justify-content: space-around;
				align-items: center;
			}
		}

		.loading {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}

		.middle_bottom {
			color: darkgray;
			text-align: center;
		}
	}

	.bottom {
		display: flex;
		position: absolute;
		bottom: 0;
		justify-content: center;
		align-items: center;
		padding: 9.17rpx 0;
		background-color: #fff;
	}
</style>